package com.housediyadmin.view.components
{
	import com.housediyadmin.events.bubbleEvents.DeleteBubbleEvent;
	import com.housediyadmin.events.bubbleEvents.UploadDoneEvent;
	import com.housediyadmin.model.PicModel;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.FileReferenceList;
	import flash.net.URLRequest;
	import flash.system.Security;
	
	import mx.binding.utils.BindingUtils;
	import mx.controls.Alert;
	import mx.controls.DataGrid;
	
	import org.robotlegs.mvcs.Mediator;
	
	/**
	 * 
	 * @author liaoruohuai
	 * 
	 */
	public class UploadPicCompMediator extends Mediator
	{
		[Inject]
		public var view:UploadPicComp;
		[Inject]
		public var model:PicModel;
		
		private var fileRefs: FileReferenceList = new FileReferenceList();
		public var urlrequest: URLRequest = new URLRequest("http://localhost/housediyadmin/RoomUploadService.aspx");
		
		private var singleThreadFiles: Array = [];
		
		[Bindable]
		private var useSingleThread: Boolean = true;
		
		private var deleteIndex:int;
		
		override public function onRegister():void
		{
			Security.allowDomain("*");
			fileRefs.addEventListener(Event.SELECT, fileSelectHandler);
			fileRefs.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			fileRefs.addEventListener(Event.COMPLETE, completeHandler);
			addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);   
			BindingUtils.bindProperty(view.files, "dataProvider", model, "selectedFiles");
			view.files.addEventListener(Event.CHANGE, showImage);
			view.selectFileButton.addEventListener(MouseEvent.CLICK, selectFile);
			view.clearButton.addEventListener(MouseEvent.CLICK, clearList);
			view.uploadButton.addEventListener(MouseEvent.CLICK, upLoad);
			view.checkboxSingleThread.selected = !useSingleThread;
			view.checkboxSingleThread.addEventListener(Event.CHANGE, isUseSingleThread);
			view.addEventListener(DeleteBubbleEvent.DELETE_PIC,singleDelete);
			//view.files.addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);
			dispatch(new UploadDoneEvent(UploadDoneEvent.UPLOAD_DONE));
		}
		private function test(event:MouseEvent):void
		{
			Alert.show("ok");
		}
		private function selectFile(e: Event): void
		{
			fileRefs.browse([new FileFilter("Images (*.jpg, *.dae, *.gif, *.png)", "*.jpg;*.dae;*.gif;*.png"), new FileFilter("所有文件(*.*)", "*.*")]);
		}
		private function fileSelectHandler(event: Event): void
		{
			for each (var f: FileReference in fileRefs.fileList)
			{
				model.selectedFiles.addItem(f);
				model.currentFiles.addItem(f);
			}
		}
		private function uploadFile(): void
		{               
			for each (var f: FileReference in model.selectedFiles)
			{           
				try
				{
					f.upload(urlrequest);
					dispatch(new UploadDoneEvent(UploadDoneEvent.UPLOAD_DONE));
				}
				catch (e: Error)
				{
					Alert.show(e.message);
				}
			}               
		}
		private function singleThreadUploadFile(): void
		{
			//FIFO：逐个从列表中取出，进行同步上传					                    
			if (singleThreadFiles.length > 0)						                   
			{							                       
				var f: FileReference = singleThreadFiles.pop() as FileReference;
				f.addEventListener(Event.COMPLETE, doSingleUploadFileComplete);	
				f.upload(urlrequest);
				dispatch(new UploadDoneEvent(UploadDoneEvent.UPLOAD_DONE));
				f.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			}					  
		}
		
		private function doSingleUploadFileComplete(event: Event): void				  
		{					
			var f: FileReference = event.target as FileReference;					  
			f.removeEventListener(Event.COMPLETE, doSingleUploadFileComplete);					  
			singleThreadUploadFile();					  
		}		  
		private function ioErrorHandler(e:IOErrorEvent): void				  
		{					
			Alert.show(e.text);					  
		}				  
		private function completeHandler(e: Event): void				  
		{	
			view.img.source = e.target.data;
			dispatch(new UploadDoneEvent(UploadDoneEvent.UPLOAD_DONE));
		}				  
		private function showImage(e: Event): void				  
		{               					
			var f: FileReference = (e.target as DataGrid).selectedItem as FileReference;					  
			f.addEventListener(Event.COMPLETE, completeHandler);					  
			f.load();	
			/*view.img.width = */
		}				  
		public function removeFile(f: FileReference): void				  
		{					
			var index: int = model.selectedFiles.getItemIndex(f);					  
			if (index != -1)						
				model.selectedFiles.removeItemAt(index);					      
		}				
		public function clearList(e:Event):void
		{
			model.selectedFiles.removeAll();
		}
		public function isUseSingleThread(e:Event):void
		{
			useSingleThread = !view.checkboxSingleThread.selected;
		}
		public function upLoad(e:Event):void
		{
			view.dispatchEvent(new UploadDoneEvent(UploadDoneEvent.UPLOAD_DONE));
			if (useSingleThread)
			{
				singleThreadFiles = model.selectedFiles.toArray().concat();
				singleThreadFiles.reverse();
				singleThreadUploadFile();
			}
			else
			{
				uploadFile();
			}
		}
		
		private function singleDelete(event:DeleteBubbleEvent):void
		{
			deleteIndex = model.selectedFiles.getItemIndex(event.f);
			Alert.yesLabel = "是";
			Alert.noLabel = "否";
			Alert.show("删除该图片吗？", "警告", 1|2, null, singleDeleteHandler);
		}
		
		private function singleDeleteHandler(event:Event):void
		{
			if (deleteIndex != -1)						
				model.selectedFiles.removeItemAt(deleteIndex);
		}
	}
}